﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;


namespace ArcMap_AddIn_Tools.Core.NETWrapper
{
    
    public static class ReflectionWrapper
    {

        //通过反射调用私有方法
        //包括时间的方法，具体传参待定
        public static void InvokeMethod(object obj, string metholdName, object[] parameters)
        {
            var metholdInfo = obj.GetType().GetMethod(metholdName, BindingFlags.NonPublic | BindingFlags.Instance);
            if (metholdInfo == null)
            {
                return;
            }
            metholdInfo.Invoke(obj, parameters);
        }


        //通过反射调用私有变量
        //通过fieldinfo对象完成对变量的读写工作
        public static System.Reflection.FieldInfo GetFieldInfo(object obj, string strFieldName)
        {
            var fieldInfo = obj.GetType().GetField(strFieldName, BindingFlags.NonPublic | BindingFlags.Instance);
            if (fieldInfo != null)
            {
                return fieldInfo;
            }
            return null;
        }

        //获取引用
        public static object GetFieldVar(object obj,string strFieldName)
        {
            var fieldInfo = obj.GetType().GetField(strFieldName, BindingFlags.NonPublic | BindingFlags.Instance);
            object objVar = null;
            if (fieldInfo != null)
            {
                objVar = fieldInfo.GetValue(obj);
            }
            return objVar;
        }




        //移除事件委托中的所有事件方法
        //事件一般在控件中实现，也有可能在一般类中使用
        public  static void ClearEvent(object pControl, string pEventName)
        {

            //根据Dev的命名规则Event字段的变量名是事件名称的第一个字母小写
            //不同控件的事件命名规则可能有差异
            pEventName = pEventName.Substring(0, 1).ToLower() + pEventName.Substring(1, pEventName.Length - 1);
            

            if (pControl == null) return;
            if (string.IsNullOrEmpty(pEventName)) return;

            BindingFlags mPropertyFlags = BindingFlags.Instance | BindingFlags.Public
                | BindingFlags.Static | BindingFlags.NonPublic;//筛选
            BindingFlags mFieldFlags = BindingFlags.Static | BindingFlags.NonPublic;
            Type controlType = pControl.GetType();
            System.Reflection.PropertyInfo propertyInfo = controlType.GetProperty("Events", mPropertyFlags);
            EventHandlerList eventHandlerList = (EventHandlerList)propertyInfo.GetValue(pControl, null);//事件列表
            System.Reflection.FieldInfo fieldInfo = controlType.GetField(pEventName, mFieldFlags);
            Delegate d = eventHandlerList[fieldInfo.GetValue(pControl)];

            if (d == null) return;
            //EventInfo eventInfo = controlType.GetEvent(pEventName);         
            foreach (Delegate dx in d.GetInvocationList())
                eventHandlerList.RemoveHandler(fieldInfo.GetValue(pControl), dx);//移除已订阅的pEventName类型事件
        }




    }
}
